package de.davvid.contracts;

import javax.microedition.lcdui.*;

import java.util.Date;
import java.util.Calendar;
import de.davvid.core.TimeRecordsMIDlet;

public class CreateContractMenu extends Form implements CommandListener {
	private TimeRecordsMIDlet midlet;

	private DateField beginField, endField;
	private TextField hoursField;
	private Command store;

	public CreateContractMenu(TimeRecordsMIDlet midlet) {
		super("Create Contract");
		this.midlet=midlet;
		
		// Find first of next month
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, 1);
		Date firstOfMonth = new Date(cal.getTime().getTime());
		// duration 3 months
		int month = cal.get(Calendar.MONTH);
		if (month <= 9) {
			cal.set(Calendar.MONTH, month+3);
		}else {
			cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+1);
			cal.set(Calendar.MONTH, month+3-12);
		}
		Date lastOfMonth = cal.getTime();
		lastOfMonth.setTime(lastOfMonth.getTime()-24*60*60*1000);
		//Form elements
		beginField = new DateField("Begin", DateField.DATE);
		beginField.setDate(firstOfMonth);
		endField = new DateField("End", DateField.DATE);
		endField.setDate(lastOfMonth);
		hoursField = new TextField("Hours per month","20",2,TextField.DECIMAL);

		append(beginField);
		append(endField);
		append(hoursField);

		//Commands
		store = new Command("Store",Command.OK,0);
		addCommand(store);
		addCommand(new Command("Cancel",Command.CANCEL,1));

		setCommandListener(this);
	}

	public void commandAction(Command c, Displayable d) {
		if(c==store) {
			try {
				Date begin = beginField.getDate();
				Date end = endField.getDate();
				if(begin == null || end==null ) 
					throw new IllegalArgumentException("Please enter a date");
				int hours=0;
				try {
					hours = Integer.parseInt(hoursField.getString());
				} catch(NumberFormatException e) {
					throw new IllegalArgumentException("No number in hours field.");
				}

				midlet.contractDB.addContract(new Contract(begin,end,hours));
				midlet.showContractList();

			} catch(IllegalArgumentException e) {
				Alert a = new Alert("Error",e.getMessage(),null,AlertType.ERROR);
				a.setTimeout(2000);
				Display.getDisplay(midlet).setCurrent(a);	
			}
		} else {
			midlet.showContractList();
		}

	}
}
